package com.huatai.auth.handler;

import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.UnsupportedGrantTypeException;
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;

/**
 * @program: nanming-saas
 * @description: 服务端自定义异常
 * @author: songxiude
 * @create: 2024-05-29 15:06
 **/
public class HtExtendOAuth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {
	public static final int FAIL_CODE = 400;

	public ResponseEntity translate(Exception e) throws Exception {
		if (e instanceof UnsupportedGrantTypeException){
			return ResponseEntity.status(ResultCode.NONSUPPORT_GRANT_TYPE.getCode()).contentType(MediaType.APPLICATION_JSON)
				.body(MyResponseResult.failed(ResultCode.NONSUPPORT_GRANT_TYPE.getCode(), ResultCode.NONSUPPORT_GRANT_TYPE.getMsg()));
		}
		if (e instanceof InvalidTokenException) {
			return ResponseEntity.status(FAIL_CODE).contentType(MediaType.APPLICATION_JSON)
				.body(MyResponseResult.failed(ResultCode.INVALID_TOKEN.getCode(),ResultCode.INVALID_TOKEN.getMsg()));
		}
		if (e instanceof InvalidGrantException) {
			return ResponseEntity.status(ResultCode.AUTH_FAIL.getCode()).contentType(MediaType.APPLICATION_JSON)
				.body(MyResponseResult.failed(ResultCode.AUTH_FAIL.getCode(), e.getMessage()));
		}
		if (e instanceof InternalAuthenticationServiceException) {
			return ResponseEntity.status(ResultCode.AUTH_FAIL.getCode()).contentType(MediaType.APPLICATION_JSON)
				.body(MyResponseResult.failed(ResultCode.AUTH_FAIL.getCode(), e.getMessage()));
		}
		return ResponseEntity.status(ResultCode.AUTH_FAIL.getCode()).contentType(MediaType.APPLICATION_JSON)
			.body(MyResponseResult.failed(ResultCode.AUTH_FAIL.getCode(),ResultCode.AUTH_FAIL.getMsg()));
	}
}
